package com.tantinevincent.vector;

/**
 * Save vector's index and value by array, 
 * apply to the vector which contains value in every index;
 * @author Vincent
 *
 */
public class DenseVector implements IVector{
	/**
	 * the length of vector, it's a fixed number.
	 */
	private int length;
	/**
	 * store the values of vector.
	 */
	private double[] values;
	/**
	 * Initialize dense vector by vector's length.
	 * @param length the length of vector.
	 */
	public DenseVector(int length){
		this.length = length; 
		this.values = new double[length];
	}
	/**
	 * {@inheritDoc}
	 */
	@Override
	public int length() {
		return length;
	}
	/**
	 * {@inheritDoc}
	 */
	@Override
	public int[] getIndices() {
		int[] indices = new int[length];
		for(int i=0; i<=length-1; i++){
			indices[i] = i;
		}
		return indices;
	}
	/**
	 * Set value to vector in the index position.
	 * @param index the index of value where you set.
	 * @param value the value which you set.
	 */
	public void set(int index, double value) {
		if( inRange(index)  ){ // in the range
			values[index] = value;
			return;
		}
		throwIndexOutOfRangeException();
	}
	/**
	 * {@inheritDoc}
	 */
	@Override
	public double get(int index) {
		if( inRange(index)  ){ // in the range
			return values[index];
		}
		throwIndexOutOfRangeException();
		return Double.NaN; // return Not a number
	}
	/**
	 * Throw index out of range. That's it.
	 */
	private void throwIndexOutOfRangeException(){
		try {
			throw new Exception( "Index out of range." );
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(-1);
		}
	}
	private boolean inRange(int index){
		return index >= 0 && index <= length-1;
	}
}
